//
//  VideoPicker.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/1.
//

//PhotosPicker 不知道为啥视频加载加载不出来的。

import SwiftUI
import PhotosUI
import UniformTypeIdentifiers
import MobileCoreServices
import SwiftUI
import PhotosUI
import UniformTypeIdentifiers
import AVKit

enum MediaFilterType {
    case images
    case videos
    case all
}
// MARK: - MediaPicker 实现
struct MediaPicker: UIViewControllerRepresentable {
    @Binding var selectionLimit: Int
    let maxFileSizeMB: Int
    let filterType: MediaFilterType
    @Binding var isPresented: Bool
    let onComplete: ([MediaItem]) -> Void
    
    func makeUIViewController(context: Context) -> PHPickerViewController {
        var config = PHPickerConfiguration()
        // 根据传入的 mediaType 设置过滤器
        switch filterType {
        case .images:
            config.filter = .images // 只展示图片
        case .videos:
            config.filter = .videos // 只展示视频
        case .all:
            config.filter = .any(of: [.images, .videos]) // 展示图片和视频
        }
        showLog("maxItems:\(selectionLimit)")
        config.selectionLimit = selectionLimit
        config.preferredAssetRepresentationMode = .current
        
        let picker = PHPickerViewController(configuration: config)
        picker.delegate = context.coordinator
        return picker
    }
    
    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }
    
    class Coordinator: PHPickerViewControllerDelegate {
        let parent: MediaPicker
        var tempVideoURLs = [URL]()
        
        init(parent: MediaPicker) {
            self.parent = parent
        }
        
        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            parent.isPresented = false
            
            guard !results.isEmpty else {
                parent.onComplete([])
                return
            }
            
            var mediaItems = [MediaItem]()
            let dispatchGroup = DispatchGroup()
            
            for result in results {
                let itemProvider = result.itemProvider
                
                // 处理本地图片
                if itemProvider.canLoadObject(ofClass: UIImage.self) {
                    dispatchGroup.enter()
                    itemProvider.loadObject(ofClass: UIImage.self) { [weak self] image, error in
                        guard self != nil else { return }
                        defer { dispatchGroup.leave() }
                        
                        if let error = error {
                            showLog("图片加载失败: \(error)")
                            return
                        }
                        
                        guard let image = image as? UIImage else { return }
                        
                        DispatchQueue.main.async {
                            mediaItems.append(MediaItem(
                                type: .localImage(image)
                            ))
                        }
                    }
                }
                // 处理本地视频
                else if itemProvider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
                    dispatchGroup.enter()
                    
                    itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { [weak self] url, error in
                        guard let self = self else { return }
                        defer { dispatchGroup.leave() }
                        
                        if let error = error {
                            showLog("视频加载失败: \(error)")
                            return
                        }
                        
                        guard let sourceURL = url else { return }
                        // 检查文件大小
                        do {
                            let attributes = try FileManager.default.attributesOfItem(atPath: sourceURL.path)
                            if let fileSize = attributes[.size] as? Int64, fileSize > parent.maxFileSizeMB * 1024 * 1024 {
                                showToast("视频文件大小超出 \(parent.maxFileSizeMB)MB，请选择较小的视频文件。")
                                showLog("视频文件大小超出 \(parent.maxFileSizeMB)MB，请选择较小的视频文件。")
                                return
                            }
                        } catch {
                            showLog("获取文件大小失败: \(error)")
                        }
                        
                        // 创建临时文件
                        let tempFileName = UUID().uuidString + ".\(sourceURL.pathExtension)"
                        let tempDirectory = FileManager.default.temporaryDirectory
                        let tempURL = tempDirectory.appendingPathComponent(tempFileName)
                        
                        do {
                            try FileManager.default.copyItem(at: sourceURL, to: tempURL)
                            self.tempVideoURLs.append(tempURL)
                            
                            DispatchQueue.main.async {
                                mediaItems.append(MediaItem(
                                    type: .localVideo(tempURL)
                                ))
                            }
                        } catch {
                            showLog("视频复制失败: \(error)")
                        }
                    }
                }
            }
            
            dispatchGroup.notify(queue: .main) { [weak self] in
                self?.parent.onComplete(mediaItems)
                self?.cleanTempFilesAfterDelay()
            }
        }
        
        // 30分钟后清理临时文件
        private func cleanTempFilesAfterDelay() {
            DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 1800) {
                self.tempVideoURLs.forEach { url in
                    do {
                        try FileManager.default.removeItem(at: url)
                    } catch {
                        showLog("临时文件删除失败: \(error)")
                    }
                }
                self.tempVideoURLs.removeAll()
            }
        }
    }
}
